<template>
  <basic-modal
    v-bind="$attrs"
    show-confirm
    :confirm-loading="confirmLoading"
    @confirm="hanleSubmit"
  >
    <n-form ref="formRef" :model="modelForm" :rules="rules">
      <n-grid x-gap="10" y-gap="10" :cols="24">
        <n-gi :span="24">
          <n-form-item label="角色" path="roleIds">
            <n-select
              placeholder="请选择角色"
              multiple
              :options="roleList"
              value-field="id"
              label-field="roleName"
              :loading="roleListLoading"
              v-model:value="modelForm.roleIds"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="24">
          <n-form-item label="所属门店">
            <n-select
              placeholder="请选择所属门店"
              multiple
              value-field="id"
              label-field="name"
              v-model:value="modelForm.branchIds"
              :options="branches"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="24">
          <n-form-item label="登录账号" path="username">
            <n-input v-model:value="modelForm.username" :disabled="isEdit" />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="密码" path="password">
            <n-input v-model:value="modelForm.password" />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="确认密码" path="confirmPassword">
            <n-input v-model:value="modelForm.confirmPassword" />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="姓名" path="realname">
            <n-input v-model:value="modelForm.realname" />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="性别" path="sex">
            <n-select
              v-model:value="modelForm.sex"
              :options="sexOpts"
              placeholder="请选择性别"
            />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="邮箱" path="email">
            <n-input v-model:value="modelForm.email" />
          </n-form-item>
        </n-gi>
        <n-gi :span="12">
          <n-form-item label="手机号" path="phone">
            <n-input v-model:value="modelForm.phone" />
          </n-form-item>
        </n-gi>
      </n-grid>
    </n-form>
  </basic-modal>
</template>
<script setup lang="ts">
import { ref, useAttrs, watch, reactive, computed } from "vue";
import { get, isEmpty } from "lodash-es";
import { FormInst, useMessage, useNotification } from "naive-ui";
import { DictStorage } from "@/storage/dict.storage";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import {
  getAllClientRoles,
  addClientUser,
  editClientUser,
} from "@/api/user/user.api";
import { getAllBranches } from "@/api/branches/branches.api";
import { IUserModalProps } from "./props";

const $emits = defineEmits(["createSuccess", "editSuccess"]);

const props = withDefaults(defineProps<IUserModalProps>(), {
  actionType: ActionTypeEnum.ADD,
});

const sexOpts = DictStorage.getDictItemsByCode("sex");

const $attrs = useAttrs();
const message = useMessage();
const notification = useNotification()

const gotRoleListFlag = ref<boolean>(false);
const roleListLoading = ref<boolean>(false);
const roleList = ref<any[]>([]);
const confirmLoading = ref<boolean>(false);
const formRef = ref<FormInst | null>(null);
const branches = ref<any[]>([]);

const modelForm = reactive({
  id: "",
  branchIds: [],
  roleIds: [],
  username: "",
  realname: "",
  password: "",
  confirmPassword: "",
  sex: undefined,
  email: "",
  phone: "",
});

const isEdit = computed(() => {
  return props.actionType === ActionTypeEnum.EDIT;
});

watch(
  () => $attrs.show,
  (newVal) => {
    if (newVal) {
      init();
    } else {
      setTimeout(handleRefresh, 50);
    }
  }
);

watch(
  () => props.userDetail,
  (newVal) => {
    if (newVal && !isEmpty(newVal)) {
      modelForm.id = newVal.id;
      modelForm.roleIds = newVal.roles.map((item: any) => item.id);
      modelForm.username = newVal.username;
      modelForm.realname = newVal.realname;
      modelForm.email = newVal.email;
      modelForm.phone = newVal.phone;
      modelForm.sex = newVal.sex ? "" + newVal.sex : undefined;
      modelForm.branchIds = newVal.branchIds;
    }
  }
);

const refresh = () => {};

const init = () => {
  handleGetAllBranches();
  handleGetAllRoleList();
};

const handleGetAllBranches = async () => {
  const result = await getAllBranches();
  branches.value = get(result, "result") || [];
};

const handleGetAllRoleList = async () => {
  if (gotRoleListFlag.value) {
    return;
  }
  roleListLoading.value = true;
  try {
    const result = await getAllClientRoles();
    roleList.value = get(result, "result") || [];
    gotRoleListFlag.value = true;
  } finally {
    roleListLoading.value = false;
  }
};

const handleAddUser = async () => {
  confirmLoading.value = true;
  try {
    const result = await addClientUser(modelForm);
    console.log(result);
    $emits("createSuccess");
    message.success("添加成功");
  } finally {
    confirmLoading.value = false;
  }
};

const handleEditUser = async () => {
  confirmLoading.value = true;
  try {
    const result = await editClientUser(modelForm);
    $emits("editSuccess");
    message.success("编辑成功");
  } finally {
    confirmLoading.value = false;
  }
};

const rules = computed(() => {
  return {
    username: [
      {
        required: !isEdit.value,
        message: "请输入登录账号",
        trigger: ["blur", "input"],
      },
    ],
    password: [
      {
        required: !isEdit.value,
        message: "请输入密码",
        trigger: ["blur", "input"],
      },
    ],
    confirmPassword: [
      {
        required: !isEdit.value,
        message: "请输入确认密码",
        trigger: ["blur", "input"],
      },
      {
        validator: (rule, value) => {
          if (value !== modelForm.password) {
            return new Error("两次输入的密码不一致");
          }
          return true;
        },
        trigger: ["blur", "input"],
      },
    ],
    realname: [
      {
        required: true,
        message: "请输入姓名",
        trigger: ["blur", "input"],
      },
    ],
    sex: [
      {
        required: true,
        message: "请选择性别",
        trigger: ["blur", "change"],
      },
    ],
    phone: [
      {
        required: true,
        message: "请输入手机号",
        trigger: ["blur", "input"],
      },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: "请输入正确的手机号格式",
        trigger: ["blur", "input"],
      },
    ],
  };
});

const handleRefresh = () => {
  modelForm.id = "";
  modelForm.confirmPassword = "";
  modelForm.password = "";
  modelForm.roleIds = [];
  modelForm.branchIds = [];
  modelForm.username = "";
  modelForm.realname = "";
  modelForm.sex = undefined;
  modelForm.email = "";
  modelForm.phone = "";
};

const hanleSubmit = async () => {
  formRef.value?.validate(async (errors) => {
    if (errors) {
      message.error("请正确输入表单项");
      return;
    }
    if (props.actionType === ActionTypeEnum.ADD) {
      handleAddUser();
    } else {
      handleEditUser();
    }
  });
};
</script>
